package com.hexiang.config;

import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.SimpleTrigger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.*;

import com.hexiang.job.MySecondJob;

@Configuration
public class QuartzConfig {
    /********** 配置两个 JobDetail **********/
    // 通过 MethodInvokingJobDetailFactoryBean 类配置 JobDetail
    @Bean
    MethodInvokingJobDetailFactoryBean jobDetail1() {
        MethodInvokingJobDetailFactoryBean bean =
                new MethodInvokingJobDetailFactoryBean();
        bean.setTargetBeanName("myFirstJob");
        bean.setTargetMethod("sayHello");
        return bean;
    }
 
    // 通过 JobDetailFactoryBean 来实现 JobDetail
    @Bean
    JobDetailFactoryBean jobDetail2() {
        JobDetailFactoryBean bean = new JobDetailFactoryBean();
        bean.setJobClass(MySecondJob.class);
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("name","sang");
        bean.setJobDataMap(jobDataMap);
        bean.setDurability(true);
        return bean;
    }
 
    /********** 创建两个 Trigger **********/
    // 创建一个 SimpleTrigger
    @Bean
    SimpleTriggerFactoryBean simpleTrigger() {
        SimpleTriggerFactoryBean bean = new SimpleTriggerFactoryBean();
        bean.setJobDetail(jobDetail1().getObject()); // 设置 jobDetail
        bean.setRepeatCount(3); // 任务循环次数为3（总共会执行4次）
        bean.setStartDelay(2000); // 任务启动延迟2秒执行
        bean.setRepeatInterval(2000);  // 任务的时间间隔为2秒
        return bean;
    }
 
    // 创建一个 CronTrigger
    @Bean
    CronTriggerFactoryBean cronTrigger() {
        CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
        bean.setJobDetail(jobDetail2().getObject()); // 设置 jobDetail
        bean.setCronExpression("* * * * * ?"); // 设置 Cron 表达式
        return bean;
    }
 
    /********** 创建 SchedulerFactory **********/
    @Bean
    SchedulerFactoryBean schedulerFactory() {
        // 通过 SchedulerFactoryBean 创建 SchedulerFactor
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        // 配置两个 Trigger
        SimpleTrigger simpleTrigger = simpleTrigger().getObject();
        CronTrigger cronTrigger = cronTrigger().getObject();
        bean.setTriggers(simpleTrigger,cronTrigger);
        return bean;
    }
}